package com.webmarmun;

import java.awt.Component;
import java.awt.Image;
import java.awt.Toolkit;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;

public class Dodavanje extends javax.swing.JFrame {

    public String serverName = "localhost";
    public String mydatabase = "porotnici";
    public String url = "jdbc:mysql://" + serverName + "/" + mydatabase + "?useUnicode=true&characterEncoding=utf8";
    public String username = "root";
    public String password = "";
    public int BrojSati;
    float rsq = 0;
    float prev = 0;
    float pau = 0;

    public Dodavanje() {
        initComponents();
        java.net.URL url1 = ClassLoader.getSystemResource("com/webmarmun/camera.png");
        Toolkit kit = Toolkit.getDefaultToolkit();
        Image img = kit.createImage(url);
        this.setIconImage(img);

        try {

            java.sql.Connection connection = null;
            connection = DriverManager.getConnection(url, username, password);

            java.sql.PreparedStatement t = connection.prepareStatement("SELECT * from fiksno");
            ResultSet trs = null;
            trs = t.executeQuery();
            while (trs.next()) {
                rsq = trs.getFloat("radni_sat");
                prev = trs.getFloat("prevoz");
                pau = trs.getFloat("pausalno");
            }
            radnisat.setText(Float.toString(rsq));
            prev = prev * 2;
            prevoz.setText(Float.toString(prev));
            pausalno.setText(Float.toString(pau));
            brojsati.setText("0");
            ukupno.setText("0");
            java.sql.PreparedStatement i = connection.prepareStatement("SELECT * from sudije WHERE Prezime_Ime_Sudije LIKE ? ");
            i.setString(1, "%" + por.getText() + "%");

            ResultSet rs = null;
            rs = i.executeQuery();
            int r = 0;
            String[] options = new String[rs.getMetaData().getColumnCount()];
            while (rs.next()) {
            }

        } catch (SQLException ex) {
            Logger.getLogger(Izmena.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jDateChooser1 = new com.toedter.calendar.JDateChooser();
        jLabel5 = new javax.swing.JLabel();
        brojsati = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        radnisat = new javax.swing.JTextField();
        jLabel14 = new javax.swing.JLabel();
        prevoz = new javax.swing.JTextField();
        jLabel16 = new javax.swing.JLabel();
        pausalno = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        napomena = new javax.swing.JTextArea();
        jLabel7 = new javax.swing.JLabel();
        ukupno = new javax.swing.JTextField();
        jLabel18 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jComboBox2 = new javax.swing.JComboBox();
        por = new javax.swing.JTextField();
        por2 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18));
        jLabel1.setText("Додавање новог решења");
        jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 11, -1, -1));

        jButton1.setBackground(new java.awt.Color(153, 255, 153));
        jButton1.setText("Сними");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 410, 84, 47));

        jButton2.setBackground(new java.awt.Color(255, 51, 51));
        jButton2.setText("Одустани");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(620, 410, -1, 47));

        jLabel2.setText("Судија:");
        jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 70, -1, -1));

        jLabel3.setText("Поротник:");
        jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 64, -1, -1));

        jLabel4.setText("Број сати:");
        jPanel1.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 140, -1, -1));
        jPanel1.add(jDateChooser1, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 140, 120, 30));

        jLabel5.setText("Датум:");
        jPanel1.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 140, -1, -1));

        brojsati.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                brojsatiKeyReleased(evt);
            }
        });
        jPanel1.add(brojsati, new org.netbeans.lib.awtextra.AbsoluteConstraints(380, 140, 110, 30));

        jLabel12.setText("Цена по сату:");
        jPanel1.add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 230, -1, -1));
        jPanel1.add(radnisat, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 230, 250, 30));

        jLabel14.setText("Превоз:");
        jPanel1.add(jLabel14, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 280, -1, -1));
        jPanel1.add(prevoz, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 280, 250, 30));

        jLabel16.setText("Паушално:");
        jPanel1.add(jLabel16, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 330, -1, -1));
        jPanel1.add(pausalno, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 330, 250, 30));

        napomena.setColumns(20);
        napomena.setRows(5);
        jScrollPane1.setViewportView(napomena);

        jPanel1.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(470, 230, 350, 100));

        jLabel7.setText("Напомена:");
        jPanel1.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 230, -1, -1));
        jPanel1.add(ukupno, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 400, 160, 40));

        jLabel18.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel18.setText("Укупно:");
        jPanel1.add(jLabel18, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 400, -1, -1));

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Име судије" }));
        jPanel1.add(jComboBox1, new org.netbeans.lib.awtextra.AbsoluteConstraints(540, 90, 280, 40));

        jComboBox2.setEditable(true);
        jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Име поротника" }));
        jPanel1.add(jComboBox2, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 90, 290, 40));

        por.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                porKeyReleased(evt);
            }
        });
        jPanel1.add(por, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 60, 290, -1));

        por2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                por2KeyReleased(evt);
            }
        });
        jPanel1.add(por2, new org.netbeans.lib.awtextra.AbsoluteConstraints(540, 60, 280, -1));

        getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, 850, 470));

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-901)/2, (screenSize.height-545)/2, 901, 545);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        this.dispose();
         new TableFromDatabase().setVisible(true);
    }//GEN-LAST:event_jButton2ActionPerformed

    private void porKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_porKeyReleased
        try {

            java.sql.Connection connection = null;
            connection = DriverManager.getConnection(url, username, password);

            java.sql.PreparedStatement t = connection.prepareStatement("SELECT * from porotnik");
            ResultSet trs = null;
            trs = t.executeQuery();
            while (trs.next()) {
                jComboBox2.addItem(trs.getString("ime"));

            }
            java.sql.PreparedStatement i = connection.prepareStatement("SELECT * from porotnik WHERE ime LIKE ? ");
            i.setString(1, "%" + por.getText() + "%");

            ResultSet rs = null;
            rs = i.executeQuery();
            int r = 0;
            String[] options = new String[rs.getMetaData().getColumnCount()];
            while (rs.next()) {

                options[r] = rs.getString("ime");
                //jComboBox2.addItem(rs.getString("Prezime_Ime_Sudije"));
                r++;
            }




            Pattern p = Pattern.compile(por.getText());
            //jComboBox2.setEditable(true);

            for (int n = 0; n < options.length; n++) {
                String elem = options[n];
                // jComboBox2.addItem(options[n]);
                Matcher m = p.matcher(elem);
                if (m.find()) {
                    jComboBox2.setSelectedItem(options[n]);
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(Izmena.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_porKeyReleased

    private void por2KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_por2KeyReleased
        try {

            java.sql.Connection connection = null;
            connection = DriverManager.getConnection(url, username, password);

            java.sql.PreparedStatement t = connection.prepareStatement("SELECT * from sudije");
            ResultSet trs = null;
            trs = t.executeQuery();
            while (trs.next()) {
                jComboBox1.addItem(trs.getString("Prezime_Ime_Sudije"));

            }
            java.sql.PreparedStatement i = connection.prepareStatement("SELECT * from sudije WHERE Prezime_Ime_Sudije LIKE ? ");
            i.setString(1, "%" + por2.getText() + "%");

            ResultSet rs = null;
            rs = i.executeQuery();
            int r = 0;
            String[] options = new String[rs.getMetaData().getColumnCount()];
            while (rs.next()) {

                options[r] = rs.getString("Prezime_Ime_Sudije");
                //jComboBox2.addItem(rs.getString("Prezime_Ime_Sudije"));
                r++;
            }




            Pattern p = Pattern.compile(por2.getText());
            //jComboBox2.setEditable(true);

            for (int n = 0; n < options.length; n++) {
                String elem = options[n];
                // jComboBox2.addItem(options[n]);
                Matcher m = p.matcher(elem);
                if (m.find()) {
                    jComboBox1.setSelectedItem(options[n]);
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(Izmena.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_por2KeyReleased

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        String DatumUpisa = null;
        Component frame1 = null;
        String dateString = null;
        int zadnjiSu = 0;

        if (jDateChooser1.getDate() ==null) {

            JOptionPane.showMessageDialog(frame1, "Грешка !\n Морате уписати датум решења !", "Први основни суд у Београду", JOptionPane.WARNING_MESSAGE);
        }else if (jComboBox2.getSelectedItem().equals("Име поротника")) {
            JOptionPane.showMessageDialog(frame1, "Грешка !\n Морате изабрати име поротника", "Први основни суд у Београду", JOptionPane.WARNING_MESSAGE);

        } else if (jComboBox1.getSelectedItem().equals("Име судије")) {
            JOptionPane.showMessageDialog(frame1, "Грешка !\n Морате изабрати име судије", "Први основни суд у Београду", JOptionPane.WARNING_MESSAGE);
        } else if (brojsati.getText().equals("")) {
            JOptionPane.showMessageDialog(frame1, "Грешка !\n Морате уписати број сати", "Први основни суд у Београду", JOptionPane.WARNING_MESSAGE);



        } else {
            Date dateFromDateChooser = jDateChooser1.getDate();
            dateString = String.format("%1$td-%1$tm-%1$tY", dateFromDateChooser);

            try {



                java.sql.Connection connection = null;
                connection = DriverManager.getConnection(url, username, password);
                try {
                    java.sql.PreparedStatement t = connection.prepareStatement("SELECT * from porotnik where ime = ?");
                    t.setString(1, jComboBox2.getSelectedItem().toString());
                    ResultSet trs = null;
                    trs = t.executeQuery();
                    while (trs.next()) {
                        DatumUpisa = trs.getString("datum");
                    }

                    java.sql.PreparedStatement su = connection.prepareStatement("SELECT su from evidencija order by id DESC limit 1");
                    ResultSet rsu = null;
                    rsu = su.executeQuery();
                    while (rsu.next()) {
                        zadnjiSu = rsu.getInt("su");
                    }
                    if (DatumUpisa.equals(dateString)) {
                        JOptionPane.showMessageDialog(frame1, "Грешка !\n Овај поротник је већ уписан у евиденцију за данашњи дан !", "Први основни суд у Београду", JOptionPane.WARNING_MESSAGE);
                    }else{
                        java.sql.PreparedStatement u = connection.prepareStatement("UPDATE porotnik set datum=? where ime=?");
                        u.setString(1,dateString);
                        u.setString(2,jComboBox2.getSelectedItem().toString());
                        u.executeUpdate();
                    
                    java.sql.PreparedStatement i = connection.prepareStatement("INSERT INTO evidencija (su,datum,ime_porotnika,mesto,ime_sudije,broj_sati,po_satu,prevoz,pausalno,ukupno,napomena) values(?,?,?,?,?,?,?,?,?,?,?)");
                    i.setInt(1, zadnjiSu + 1);
                    i.setString(2, dateString);
                    i.setString(3, jComboBox2.getSelectedItem().toString());
                    i.setString(4, "Београд");
                    i.setString(5, jComboBox1.getSelectedItem().toString());
                    i.setInt(6, Integer.parseInt(brojsati.getText()));
                    i.setFloat(7, Float.parseFloat(radnisat.getText()));
                    i.setFloat(8, Float.parseFloat(prevoz.getText()));
                    i.setFloat(9, Float.parseFloat(pausalno.getText()));
                    i.setFloat(10, Float.parseFloat(ukupno.getText()));
                    i.setString(11, napomena.getText());
                    i.executeUpdate();
                    connection.close();
                    this.dispose();
                     new TableFromDatabase().setVisible(true);
                  }
                } catch (SQLException ex) {
                    Logger.getLogger(Izmena.class.getName()).log(Level.SEVERE, null, ex);
                }

            } catch (SQLException ex) {
                Logger.getLogger(Dodavanje.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void brojsatiKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_brojsatiKeyReleased
//        String brsati = brojsati.getText();
//        BrojSati = Integer.parseInt(brsati);
//        Float U = (BrojSati * rsq) + prev + pau;
//        ukupno.setText(U.toString());
         rsq = Float.parseFloat(radnisat.getText());
        prev = Float.parseFloat(prevoz.getText());
        pau = Float.parseFloat(pausalno.getText());
        String brsati = brojsati.getText();
        BrojSati = Integer.parseInt(brsati);
        Float U = (BrojSati * rsq) + prev + pau;
        ukupno.setText(U.toString());

    }//GEN-LAST:event_brojsatiKeyReleased

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {

                new Dodavanje().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField brojsati;
    public static javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox2;
    private com.toedter.calendar.JDateChooser jDateChooser1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea napomena;
    private javax.swing.JTextField pausalno;
    private javax.swing.JTextField por;
    private javax.swing.JTextField por2;
    private javax.swing.JTextField prevoz;
    private javax.swing.JTextField radnisat;
    private javax.swing.JTextField ukupno;
    // End of variables declaration//GEN-END:variables
}
